
// snake
let joystick = require("joystick");

// 生成了一个 代码组件的模板类;
cc.Class({
    extends: cc.Component,

    // 属性列表
    properties: {

        stick: {
            type: joystick,
            default: null,
        },

        FIXED_TIME: 0.03,
        ITEM_DISTANCE: 25, // 每节蛇的距离

        speed: 100,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},
    // star 函数: 开始运行的时候调用，初始化;
    start () {
        // this: 指的时当前的组件实例;
        // this.node, 指的时当前组件实例所在的节点;
        this.fixed_time = 0;

        // 开始的时候, 就可以根据fixed_time来采集我们的蛇尾到蛇头的数据;
        this.pos_set = []; // 要从蛇尾蠕动到蛇头所经过的所有位置;

        // 蛇尾走到蛇头的距离
        let len = this.ITEM_DISTANCE * (this.node.children.length - 1);
        // 蛇尾走到蛇头要用的总时间
        let total_time = len / this.speed;
        // 每一帧我们用fixedupdate来模拟，所以
        let frame_time = this.FIXED_TIME;
        let block = this.speed * frame_time; // 每次update 蠕动的距离

        let now_len = 0;
        let xpos = len;
        while(now_len < len) {
            this.pos_set.push(cc.v2(xpos, 0)); // 把坐标保存到数组;
            now_len += block;
            xpos -= block;
        }
        this.pos_set.push(cc.v2(0, 0)); // 按照每秒fixed_time来计算出来，蛇头从蛇尾蠕动到蛇头所经过的位置点的集合;

        // 采集每一节在开始的时候，所在的位置数组的索引;
        let block_num = 0;
        for(let i = this.node.children.length - 1; i >= 0; i --) {
            let now_index = Math.floor((block_num * this.ITEM_DISTANCE) / block);
            this.node.children[i].end_cur_index = now_index;
            this.node.children[i].setPosition(this.pos_set[now_index]);
            block_num++;
        }

    },

    fixed_update(dt) {
        if(this.stick.dir === -1) { // 表示摇杆停止了，没有摇杆消息;
            return;
        }

        let r = this.stick.radius; // 弧度;
        let head = this.node.children[0];
        let s = this.speed * dt;

        let sx = s * Math.cos(r);
        let sy = s * Math.sin(r);

        head.x += sx;
        head.y += sy;

        this.pos_set.push(head.getPosition());

        let degree = r * 180 / Math.PI;
        degree = 360 - degree;

        // head.rotation = degree;
        head.angle = -degree;


        for(let i = 1; i < this.node.childrenCount; i ++) {
            let item = this.node.children[i];
            let src = item.getPosition();
            item.end_cur_index ++;
            item.setPosition(this.pos_set[item.end_cur_index]);
            let dst = item.getPosition();

            let dir = src.sub(dst);

            r = Math.atan2(dir.y, dir.x);
            degree = r * 180 / Math.PI;
            degree = 360 - degree;

            // item.rotation = degree;
            item.angle = -degree;
        }


    },

    // update函数: 游戏每次刷新的时候调用;
    update (dt) {
        this.fixed_time += dt;
        while(this.fixed_time > this.FIXED_TIME) {
            this.fixed_update(this.FIXED_TIME);
            this.fixed_time -= this.FIXED_TIME;
        }
    },
});
